"""StaffLog Checkin - Predesys service
@version: 0.1
@license: GPL 3.0 (see "license" file)
@author: Jose A. Jimenez <jajimc@gmail.com>, Miguel Centeno <miguelcent@gmail.com>"""

import sys
sys.dont_write_bytecode = True
import os
DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
import time
import math
sys.path.append(os.path.join(DIR, "../core"))
import data
import users

### SERVICE TEMPLATE ###
def get_service_id():
    return "stafflog-checkin"
    
def get_version():
    return "0.1"
    
def get_service_name():
    return "StaffLog Checkin"
    
def get_author():
    return "Jose A. Jimenez <jajimc@gmail.com>, Miguel Centeno <miguelcent@gmail.com>"
    
def run(userId, args):
    userResult = ""

    try:
        # Received distances
        distanceEyeEyeHor = args[0]
        distanceEyeNoseVer = args[1]
        distanceEyeNoseHor = args[2]
        distanceNoseMouthVer = args[3]

        # Retrieve DB distances (if registered) for each user
        userDistances = []
        dbConnection = data.open_connection()
        
        statement = "select id, dist_eye_eye_hor, dist_eye_nose_ver, dist_eye_nose_hor, dist_nose_mouth_ver"
        statement += " from users, serv_stafflog_distances where id=user_id;"
        
        result = data.execute(dbConnection, statement)
        for row in result:
            userDistances.append([row["id"], row["dist_eye_eye_hor"], row["dist_eye_nose_ver"], row["dist_eye_nose_hor"], row["dist_nose_mouth_ver"]])
        result.close()
        
        # Compare each user distances with input ones
        for distances in userDistances:
            cond1 = math.fabs(int(distances[1]) - distanceEyeEyeHor) <= 10
            cond2 = math.fabs(int(distances[2]) - distanceEyeNoseVer) <= 15
            cond3 = math.fabs(int(distances[3]) - distanceEyeNoseHor) <= 20
            cond4 = math.fabs(int(distances[4]) - distanceNoseMouthVer) <= 10
            
            if cond1 and cond2 and cond3 and cond4:
                id = distances[0]
                user = users.get_user_data(id)
                name = user.get_name()
                userResult = [id, name]
                break
                
        # If distances correspond to a registered user, log user
        if userResult != "":
            statement = "insert into serv_stafflog_log values ('%s', '%f');" % (userResult[0], time.time())
            result = data.execute(dbConnection, statement)
            result.close()
            
        data.close_connection(dbConnection)
    except:
        pass
            
    return userResult
